﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls.Expressions;
using StockMatch.Service;
using StockMatch.Service.Entity;
using StockMatch.WebSite.Models;
using QueryExpression = Titan.QueryExpression;

namespace StockMatch.WebSite.Controllers
{
    public class DayWinController : StockControllerBase
    {
        public ActionResult Index(string param)
        {
            ViewBag.Menu = "daywin";
            DayWin dayWin=new DayWin();
            if (!string.IsNullOrEmpty(param))
            {
                string[] ps = param.Split(new char[] {'&'}, StringSplitOptions.RemoveEmptyEntries);
                dayWin.FirmCapital = decimal.Parse(ps[0].Split('=')[1]);
                dayWin.RiskMargin = int.Parse(ps[1].Split('=')[1]);
                dayWin.TotalTrade = decimal.Parse(ps[2].Split('=')[1]);
                dayWin.LossWarLine = decimal.Parse(ps[3].Split('=')[1]);
                dayWin.LossOpenLine = decimal.Parse(ps[4].Split('=')[1]);
                dayWin.ManageMoney = decimal.Parse(ps[5].Split('=')[1]);
                dayWin.StartTime = int.Parse(ps[6].Split('=')[1]);
                dayWin.IsFree = bool.Parse(ps[7].Split('=')[1]);
                dayWin.Type = int.Parse(ps[8].Split('=')[1]);
            }
            else
            {
                dayWin.FirmCapital = 2000;
                dayWin.RiskMargin = 10;
            }
            return View(dayWin);
        }

        public ActionResult Free()
        {
            ViewBag.Menu = "daywin";
            ViewBag.Tag = "free";
            return View();
        }

        public ActionResult Banner()
        {
            return View();
        }

        public ActionResult Scroll()
        {
            return View();
        }

        public ActionResult Confirm(DayWin dayWin)
        {
            dayWin.Number = Guid.NewGuid().ToString();
            var result = MathProject.MathRiskMargin(dayWin.FirmCapital, dayWin.RiskMargin);

            dayWin.FirmCapital = dayWin.FirmCapital;
            dayWin.TotalTrade = dayWin.FirmCapital > 0 ? dayWin.FirmCapital + result.Principal : 0;
            dayWin.LossWarLine = result.Warning;
            dayWin.LossOpenLine = result.Open;
            dayWin.ManageMoney = result.Fee;
            if (CurrentUser != null)
            {
                User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
                ViewBag.BalanceAmount = user.BalanceAmount;
            }
            ViewBag.RiskMargin = result.Principal;
            ViewBag.Menu = "daywin";
            return View(dayWin);
        }

        public ActionResult PostConfirm(DayWin dayWin)
        {
            if (dayWin == null)
            {
                throw new ArgumentNullException("dayWin");
            }
            if (CurrentUser == null)
            {
                return Json(new { data = 2, message = "请先登录" });
            }

            DayWinProject dayWinProject = new DayWinProject();
            var result = MathProject.MathRiskMargin(dayWin.FirmCapital, dayWin.RiskMargin);

            dayWinProject.UserId = CurrentUser.UserId;//用户id
            dayWinProject.FirmCapital = dayWin.FirmCapital;//实盘资金
            dayWinProject.lever = dayWin.RiskMargin;//风险保证金（选择5，10，15）做计算用
            dayWinProject.RiskMargin = result.Principal;//风险保证金（金额）
            dayWinProject.TotalTrade = dayWin.FirmCapital > 0 ? dayWin.FirmCapital + result.Principal : 0;//总操盘资金
            dayWinProject.LossWarLine = result.Warning;//亏损警告线
            dayWinProject.LossOpenLine = result.Open;//亏损平仓线
            dayWinProject.ManageMoney = result.Fee;//账号管理费
            dayWinProject.FundTime = dayWin.FundTime;//资金使用期限
            dayWinProject.StartTime = dayWin.StartTime;//开始交易时间（当天，下个交易日）
            dayWinProject.IsFree = false;//是否是免费体验
            dayWinProject.Proportion = 100;//盈利返回（盈利全归客户）
            dayWinProject.AddTime = DateTime.Now;
            dayWinProject.ProjectState = 1;//正在验资中
            DateTime nextDate = DateTime.Now.AddDays(1);
            dayWinProject.StartProjectTime = dayWinProject.StartTime == 0
                ? DateTime.Now
                : new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, 9, 0, 0);//下个交易日
            User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
            if (user.BalanceAmount < dayWinProject.FundTime*dayWinProject.ManageMoney+dayWinProject.RiskMargin)
            {
                return Json(new {data = 3, message = "账户余额不足"});
            }
            
            if (ServiceManager.DayWinProjectService.Insert(dayWinProject))
            {
                return Json(new {data = dayWinProject.ProjectId, message = "ok"});
            }

            return Json(new {data = 0, message = "提交方案失败"});
        }

        public ActionResult Seccess(int id)
        {
            DayWinProject dayWinProject= ServiceManager.DayWinProjectService.GetDayWinProject(id);
            return View(dayWinProject);
        }

        public ActionResult Project(int id)
        {
            DayWinProject dayWinProject = ServiceManager.DayWinProjectService.GetDayWinProject(id);
            if (dayWinProject == null)
            {
                return View("~/Views/DayWin/Project404.cshtml");
            }
            #region 账号管理费
            QueryExpression query=new QueryExpression();
            query.EntityType = typeof (DayWinProjectAccount);
            query.Selects.Add(DayWinProjectAccount_.ALL);
            query.Wheres.Add(DayWinProjectAccount_.ProjectId.TEqual(dayWinProject.ProjectId));
            query.OrderBy(DayWinProjectAccount_.PayTime.Asc);
            ViewData["DayWinProjectAccount"] = ServiceManager.DayWinProjectAccountService.GetProjectAccounts(query);
            #endregion

            #region 追加保证金记录
            query = new QueryExpression();
            query.EntityType = typeof (DayWinProjectRiskMargin);
            query.Select(DayWinProjectRiskMargin_.ALL);
            query.Where(DayWinProjectRiskMargin_.ProjectId.TEqual(dayWinProject.ProjectId));
            query.OrderBy(DayWinProjectRiskMargin_.AddTime.Asc);
            DayWinProjectRiskMargins dayWinProjectRiskMargins = ServiceManager.DayWinProjectRiskMarginService.GetProjectRiskMargins(query);
            ViewData["DayWinProjectRiskMargin"] = dayWinProjectRiskMargins;
            ViewData["DayWinProjectRiskMargin0"] = dayWinProjectRiskMargins.Items.Where(p => p.AddState == 1).ToList();
            #endregion

            return View(dayWinProject);
        }

        [HttpPost]
        public ActionResult AddRiskMargin(int projectId, int riskMargin, int type)
        {
            if (riskMargin < 100)
            {
                return Json(new {data = 0, message = "追加的保证金金额不能小于100元"});
            }
            if (CurrentUser == null)
            {
                return Json(new {data = 0, message = "请先登录"});
            }
            if (ServiceManager.UserService.GetUser(CurrentUser.UserId).BalanceAmount < riskMargin)
            {
                return Json(new { data = 0, message = "账户余额不足，请充值" });
            }
            int i = ServiceManager.DayWinProjectService.AddRiskMargin(projectId, riskMargin, type);
            if (i == 2)
            {
                return Json(new {data = 0, message = "每天最多追加5次(包括取消次数)"});
            }
            if (i > 0)
            {
                return Json(new {data = 1, message = "申请追加保证金成功"});
            }
            return Json(new {data = 0, message = "申请追加保证金失败"});
        }
    }
}